var gamejs = require('gamejs');
var matchjs = require('js/match')

var Bullet = exports.Bullet = function(pLevel,orig,dest,match) {
	Bullet.superConstructor.apply(this, arguments);
	this.currentMatch = match;
	this.target = dest;
	this.count = 0;
	this.inertia = [0,0];
	this.originalImage = gamejs.image.load("resources/images/missle.png");
	 this.upgradeList = [
	                     {speed: 100, damage: 500}, // livello 0
	                     {speed: 200, damage: 200}, // livello 1
	                     {speed: 300, damage: 300}, // livello 2
	                     {speed: 350, damage: 400}, // livello 3
	                     {speed: 400, damage: 500} // livello 4
	                     ];
	this.level = pLevel;
	this.originalImage = gamejs.transform.scale(
			this.originalImage,
			[this.originalImage.getSize()[0] * (0.5), this.originalImage.getSize()[1] *  (0.5)]
	);
	this.image = this.originalImage;
	this.rect = new gamejs.Rect(orig.center,this.image.getSize());
	this.rotation =  Math.atan2(-this.rect.topleft[1]+this.target.getCoordinates()[1],-this.rect.topleft[0]+this.target.getCoordinates()[0])* 180 / Math.PI;
	this.image = gamejs.transform.rotate(this.originalImage, this.rotation);
}

/**
 * Extending Sprite with Enemy
 */
gamejs.utils.objects.extend(Bullet, gamejs.sprite.Sprite);


/**
 * Updates the position of the Bullet
 * 
 * @param {int} ms duration
 */
Bullet.prototype.update = function(msDuration) {
	if (! this.target.isDead() && this.target.isDetected())    //if the target is dead or hidden missiles not chase him
		this.rotation =  Math.atan2(-this.rect.center[1]+this.target.getCoordinates()[1],-this.rect.center[0]+this.target.getCoordinates()[0])* 180 / Math.PI;
		
	
		
	var nextMoveX=(this.upgradeList[this.level].speed * (msDuration / 1000))*Math.cos(this.rotation* Math.PI / 180) + this.inertia[0]; //the increase of the Xposition of the missile
	var nextMoveY=(this.upgradeList[this.level].speed * (msDuration / 1000))*Math.sin(this.rotation* Math.PI / 180) + this.inertia[1]; //the increase of the Yposition of the missile

	this.image = gamejs.transform.rotate(this.originalImage, this.rotation);
	this.rect.moveIp(nextMoveX,nextMoveY);
	var curRect = this.rect;
	var curDamage = this.upgradeList[this.level].damage;
	var curThis = this;
	var curMatch = this.currentMatch;
	if (! this.currentMatch.getMap().isInside(this.rect.center)){
		this.kill();
	}
	this.currentMatch.getMap().getEnemies().sprites().forEach(function (collision_list) {
		if (collision_list.rect.collideRect(curRect) && collision_list.health>0){
			curMatch.getSoundManager().playExplosion(0);
			collision_list.hit(curDamage);
			curThis.kill();
		}
	});
}